package com.hackaton;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.*;
import com.hackaton.maps.MapHelper;
import com.hackaton.maps.transport.Route;
import com.hackaton.maps.city.Vinnitsia;
import com.hackaton.ui.CustomSlidingMenu;
import com.hackaton.ui.GridFragment;
import com.hackaton.ui.SplashActivity;


public class MyActivity extends Activity {
    private TabHost tabHost;
    private CustomSlidingMenu menu;

    /**
     * Called when the activity is first created.
     */
    public static boolean isNew = false;
    static Context context;
    private LinearLayout navControls;

    LatLng startPoint;
    LatLng endPoint;
    private ImageButton startButton;
    private ImageButton endButton;
    private LatLng selectedPoint;

    private Marker markerStart;
    private Marker markerEnd;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //  MAP INIT !!!
        final GoogleMap map = findMap(R.id.the_map);
        map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                if (startPoint == null) {
                    selectedPoint = latLng;
                    navControls.setVisibility(View.VISIBLE);
                } else {
                    if (endPoint == null) {
                        selectedPoint = latLng;
                    }
                }

            }
        });
        new MapHelper(map, this);
        // -----------------------------------------

        showSplash();

        Drawable dr = this.getResources().getDrawable(android.R.color.white);
        getActionBar().setBackgroundDrawable(dr);
        navControls = (LinearLayout) findViewById(R.id.placeholder_nav_buttons);
        startButton = (ImageButton) navControls.findViewById(R.id.button_start);
        endButton = (ImageButton) navControls.findViewById(R.id.button_end);
        startButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startPoint = selectedPoint;
                endButton.setEnabled(true);
                markerStart = map.addMarker(new MarkerOptions()
                        .position(selectedPoint)
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
                markerStart.setTitle("From");
            }
        });
        endButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                endPoint = selectedPoint;
                markerEnd = map.addMarker(new MarkerOptions()
                        .position(selectedPoint)
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
                markerEnd.setTitle("To");
                //TODO start intent here

                Uri routeUri = Uri.parse("http://maps.google.com/maps?&saddr=" +
                        startPoint.latitude + "," +
                        startPoint.longitude + "&daddr=" +
                        endPoint.latitude + "," +
                        endPoint.longitude);

                Intent i = new Intent(Intent.ACTION_VIEW, routeUri);
                startActivity(i);
            }
        });
        createSlidingMenu();
        context = this;
        initTabhostInSlidingMenu();
        // test ....   -----------------------------
//        LatLng PERTH = new LatLng(49.23545013, 28.48581076);
//
//        Marker melbourne = map.addMarker(new MarkerOptions()
//                .position(PERTH)
//                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
//                .draggable(false));
//
//        melbourne.setSnippet("Snippet");
//        melbourne.setFlat(true);
//        melbourne.setTitle("Title");
        // ------------------------------------------
    }

    public static Context getContext() {
        return context;
    }

    private void createSlidingMenu() {
        CustomSlidingMenu.reinit();
        menu = CustomSlidingMenu.getInstance(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(Menu.NONE, 1, Menu.NONE, "Clear").setIcon(android.R.drawable.ic_menu_close_clear_cancel).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
//        menu.add(Menu.NONE, 3, Menu.NONE, "Logout").setIcon(R.drawable.icon_actionbar_logout).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 1:
                clearNavigation();
                if (markerEnd != null)
                    markerEnd.setVisible(false);
                if (markerStart != null)
                    markerStart.setVisible(false);
                break;
            default:
                return super.onOptionsItemSelected(item);
        }
        return false;
    }

    public void clearNavigation() {
        startPoint = null;
        endPoint = null;
        endButton.setEnabled(false);
        navControls.setVisibility(View.GONE);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 15) {
            MapHelper.getInstance().animateMapCamera(Vinnitsia.POSITION, 15);
        }

    }

    private void showSplash() {
        Intent splashScreen = new Intent(this, SplashActivity.class);
        startActivityForResult(splashScreen, 15);
    }


    public void initTabhostInSlidingMenu() {
        tabHost = (TabHost) findViewById(R.id.tabHost);
        tabHost.setup();

        GridFragment taxi = new GridFragment(0);

        GridFragment trol = new GridFragment(1);

        GridFragment tram = new GridFragment(2);

        addTab(R.drawable.ico_splash_taxi, "Маршрутка", R.id.tab1, taxi);
        addTab(R.drawable.ico_splash_trol, "Троллейбус", R.id.tab2, trol);
        addTab(R.drawable.ico_splash_tram, "Трамвай", R.id.tab3, tram);
    }

    public void addTab(int imageRes, String tabLabel, int content, Fragment fragment) {
        TabHost.TabSpec tabSpec;
        tabSpec = tabHost.newTabSpec(tabLabel);
        View tab = LayoutInflater.from(this).inflate(R.layout.layout_tabwidget, tabHost.getTabWidget(), false);
        tab.setMinimumWidth(150);

        ((TextView) tab.findViewById(R.id.tv_tabwidget_name)).setText(tabLabel);
        ((ImageView) tab.findViewById(R.id.iv_tabvidget)).setImageResource(imageRes);

        tabSpec.setIndicator(tab);
        tabSpec.setContent(content);
        tabHost.addTab(tabSpec);
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        if (!fragment.isAdded()) {
            transaction.replace(content, fragment);
        } else {
            transaction.show(fragment);
        }
        transaction.commit();
    }

    public void onResume() {
        super.onResume();
        if (isNew) {
            isNew = false;
            MapHelper.getInstance().animateMapCamera(Vinnitsia.POSITION, Vinnitsia.ZOOM);
        }
    }

    private GoogleMap findMap(int mapId) {
        return ((MapFragment) getFragmentManager().findFragmentById(mapId)).getMap();
    }
}